package com.hbnu.dao;

import com.hbnu.entity.FileStat;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.stream.Collectors;

public class UserFileDao extends JDBC{
    //获取文件详情
    public FileStat getFile(int fid) {
        try(PreparedStatement preparedStatement=getPreparedStatement(
                "select f.fname,f.created_time,sf.file_size,sf.file_md5,sf.file_path from files sf\n" +
                        "join (select file_id,fname,created_time from files_folders where fid= ? and is_deleted=0) f\n" +
                        "on sf.file_id = f.file_id;"
        )){
            preparedStatement.setInt(1,fid);
            ResultSet resultSet = preparedStatement.executeQuery();
            if(resultSet.next()){
                FileStat fileStat=new FileStat();
                fileStat.setName(resultSet.getString(1));
                fileStat.setCreated_time(resultSet.getTimestamp(2).toLocalDateTime());
                fileStat.setSize(resultSet.getLong(3));
                fileStat.setMd5(resultSet.getString(4));
                fileStat.setPath(resultSet.getString(5));
                return fileStat;
            }else {
                throw new RuntimeException("数据异常");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    //创建文件夹
    public int createFolder(String userId, int pid, String name) {
        try(PreparedStatement preparedStatement=getPreparedStatement0(
                "insert into files_folders(user_id,pid,fname,created_time) values(?,?,?,now());"
        )){
            // 设置 PreparedStatement 参数
            preparedStatement.setString(1,userId);
            preparedStatement.setInt(2,pid);
            preparedStatement.setString(3,name);
            // 执行插入操作
            if (preparedStatement.executeUpdate() > 0) {
                // 获取生成的主键
                try (ResultSet generatedKeys = preparedStatement.getGeneratedKeys()) {
                    if (generatedKeys.next()) {
                        // 获取生成的主键值（ int 类型）
                        return generatedKeys.getInt(1);
                    }
                    throw new RuntimeException("无法获取生成的主键");
                }
            }else {
                throw new RuntimeException("数据插入异常");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    //删除文件
    public boolean deleteF(int id) {
        try(PreparedStatement preparedStatement=getPreparedStatement(
                "update files_folders set is_deleted = 1 where fid=?;"
        )){
            preparedStatement.setInt(1,id);
            return preparedStatement.executeUpdate()>0;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    //删除文件夹,调用存储过程 call update_folder_delete_status(?);
    public boolean deleteFolder(int id) {
        try(PreparedStatement preparedStatement=getPreparedStatement(
                "call update_folder_delete_status(?,1);"
        )){
            preparedStatement.setInt(1,id);
            return preparedStatement.executeUpdate()>0;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    //计算文件大小
    public long sumFileSize(List<Integer> fileIdList) {
        try(Statement statement = getStatement()){
            String sql=
                    "select sum(file_size) " +
                            "from files " +
                            "where file_id in (";
            String ids = fileIdList.stream()
                    .map(String::valueOf) // 将 Integer 转为 String
                    .collect(Collectors.joining(","));
            ResultSet resultSet = statement.executeQuery(sql+ids+");");
            if (resultSet.next()){
                return resultSet.getLong(1);
            }
            throw new RuntimeException("计算文件大小异常");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }



    //修改名称
    public boolean updateFname(int id, String newName) {
        try(PreparedStatement preparedStatement=getPreparedStatement(
                "update files_folders set fname= ? where fid=?;"
        )){
            preparedStatement.setString(1,newName);
            preparedStatement.setInt(2,id);
            return preparedStatement.executeUpdate()>0;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    //修改父文件
    public boolean updatePid(int fid, int nFid){
        try(PreparedStatement preparedStatement=getPreparedStatement(
                "update files_folders set pid = ? where fid= ?;"
        )){
            preparedStatement.setInt(1,nFid);
            preparedStatement.setInt(2,fid);
            return preparedStatement.executeUpdate()>0;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }
}
